﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using Jackie.Utility;
using Jackie.Utility.CustomException;
using Jackie.Update.IBusiness;
using Jackie.Utility.CustomExtension;

namespace Jackie.Update.Publish
{
    public partial class PublishForm : Form
    {
        private XDocument config;
        private PublishManager publishManager;

        public PublishForm()
        {
            InitializeComponent();
            this.Load += new EventHandler(PublishForm_Load);
            publishManager = new PublishManager(this);
        }

        void PublishForm_Load(object sender, EventArgs e)
        {
            var systemConfigPath = Path.Combine(Application.StartupPath, "SystemConfig.xml");
            config = XDocument.Load(systemConfigPath);
            var showNames = config.Elements("Systems").Elements("System").Select(el => el.Element("ShowName").Value);
            showNames.ForEach(item => cobSystem.Items.Add(item));
        }



        private void btnPublish_Click(object sender, EventArgs e)
        {
            var systemVersion = txtSystemVersion.Text.Trim();
            var systemName = txtSystemName.Text.Trim();
            var localPath = txtLocalPath.Text.Trim();
            var discription = txtDiscription.Text.Trim();
            try
            {
                if (!localPath.EndsWith("\\"))
                    localPath += "\\";
                publishManager.Publish(systemName, localPath, systemVersion, discription);
                MessageBox.Show("发布完成！");
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (VersionExistedException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cobSystem_SelectedIndexChanged(object sender, EventArgs e)
        {
            var systemElement =
                config.Elements("Systems").Elements("System").Where(
                    el => el.Element("ShowName").Value.Equals(cobSystem.SelectedItem.ToString())).First();
            txtSystemName.Text = systemElement.Element("Name").Value;
            txtLocalPath.Text = systemElement.Element("LocalPath").Value;
        }
    }
}
